package rsj.service.usage.product;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.QueryRunnerFactory;
import rsj.api.org.entity.CurrentTableColumn;
import rsj.api.org.entity.UsageReportParam;
import rsj.service.usage.ICalculateUsage;

import java.sql.Connection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 查询机构模块-产品使用量
 *
 * @author yuanqinglong
 * @since 2021/3/12 15:21
 */
public interface IProductCalculateUsage extends ICalculateUsage {


    /**
     * 机构模块-查询接口的使用量分组累计
     *
     * @param statisticColumnEntities 查询列表的数据 不包含使用量
     * @param connection              数据库连接
     * @param statEnv                 环境（01：测试环境，02：生产环境，03：线下测试环境）
     * @param usageReportParam        请求参数
     */
    @Override
    default void queryInterfaceUsageThroughContract(List<CurrentTableColumn> statisticColumnEntities, Connection connection, String statEnv, UsageReportParam usageReportParam) {
        List<String> orgId = statisticColumnEntities.stream().map(CurrentTableColumn::getStatOrgId).distinct().collect(Collectors.toList());
        String orgValues = ICalculateUsage.assemblyInQueryConditions(orgId);
        String sql = "SELECT stat_org_id,stat_useamount,stat_prod_uid FROM sys.sys_stat WHERE stat_prod_uid LIKE '%" + usageReportParam.getStatProdUid() + "%' AND stat_org_id IN (" + orgValues + ")";
        TableNode tableNode = QueryRunnerFactory.getQueryRunner().queryLinkTableNode(connection, sql);
        List<CurrentTableColumn> tableColumns = JSON.parseArray(tableNode.toJson(), CurrentTableColumn.class);
        // 计算使用量和剩余量
        this.fillInTheRemainingUsageField(statisticColumnEntities, tableColumns, usageReportParam);
    }


    /**
     * 填写剩余使用量字段
     *
     * @param statisticColumnEntities 产品使用情况列字段（不包含剩余量字段）需通过tableColumns进行计算
     * @param tableColumns            包含剩余量的集合
     * @param usageReportParam        请求参数
     */
    @Override
    default void fillInTheRemainingUsageField(List<CurrentTableColumn> statisticColumnEntities, List<CurrentTableColumn> tableColumns, UsageReportParam usageReportParam) {
        Map<String, List<CurrentTableColumn>> groupStatisticsUsage = tableColumns.stream().collect(Collectors.groupingBy(CurrentTableColumn::getStatOrgId));
        Map<String, Integer> groupingAndAdding = new LinkedHashMap<>();
        groupStatisticsUsage.forEach((key, currentTableColumns) -> {
            // 分组后 每组的接口使用量对应累加
            AtomicInteger usage = new AtomicInteger();
            currentTableColumns.forEach(currentTableColumn -> {
                // 如果合同是组合包量 数组是多个元素
                String[] useMountArray = currentTableColumn.getStatUseamount().split(",");
                String[] uidArray = currentTableColumn.getStatProdUid().split(",");
                for (int i = 0; i < uidArray.length; i++) {
                    if (Objects.equals(uidArray[i], usageReportParam.getStatProdUid())) {
                        usage.addAndGet(Integer.parseInt(useMountArray[i]));
                    }
                }
            });
            groupingAndAdding.put(key, usage.intValue());
        });
        // 将每条产品使用情况的使用量赋值
        statisticColumnEntities.forEach(currentTableColumn -> {
            Integer statUseMount = groupingAndAdding.get(currentTableColumn.getStatOrgId());
            currentTableColumn.setStatUseamount(String.valueOf(statUseMount));
        });
        // 如果需要、计算剩余量
        this.ifYouNeedToCalculateTheRemainingAmount(statisticColumnEntities);
    }
}
